import { Input } from 'antd-mobile'
import type { InputProps } from 'antd-mobile/es/components/input'
import React, { useRef, useState } from 'react'

interface InputLimitProps extends InputProps {
    regExp: RegExp
}

export default function InputLimit(props: InputLimitProps) {
    const { value, onChange, regExp, ...rest } = props
    const [preVal, setPreVal] = useState<any>(value)

    const ref = useRef({ isOnComposition: false })
    /** 输入合成时会触发 */
    function handleComposition(evt: any) {
        console.log(evt.type, preVal, value)
        if (evt.type === 'compositionstart') {
            ref.current.isOnComposition = true
        } else if (evt.type === 'compositionend') {
            ref.current.isOnComposition = false
            /** 兼容chrome */
            const targetValue = evt.target.value
            if (regExp.test(targetValue)) {
                onChange?.(targetValue)
                setPreVal(targetValue)
                return
            }
            onChange?.(preVal)
        }
    }

    return (
        <Input
            {...rest}
            value={value}
            onCompositionStart={handleComposition}
            onCompositionEnd={handleComposition}
            onChange={(changeVal: string) => {
                if (!ref.current?.isOnComposition) {
                    if (regExp.test(changeVal) || changeVal === '' || changeVal === undefined) {
                        onChange?.(changeVal)
                        setPreVal(changeVal)
                        return
                    }
                    onChange?.(preVal)
                    return
                }
                onChange?.(changeVal)
            }}
        />
    )
}
